package com.company.project.email.controller;

import com.company.project.common.utils.DataResult;
import com.company.project.email.entity.EmailEntity;
import com.company.project.email.service.EmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;

/**
 * @author ZYF
 * @date 2021/8/24 15:57
 */
@Api(tags = "发送邮件接口")
@RestController
@RequestMapping("/email")
public class EmailController {

    @Resource
    EmailService emailService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @ApiOperation(value="发送邮箱接口")
    @PostMapping("/sendEmail")
    public DataResult sendEmail(@RequestBody EmailEntity emailEntity) throws MessagingException, UnsupportedEncodingException {
        //考虑到发送邮箱这一过程比较慢，把Id放到MQ里，让MQ去发
        emailService.save(emailEntity);
        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {

                //给消息设置过期时间（如果队列也设置了过期时间，按两者最小的过期时间为准）
                message.getMessageProperties().setExpiration("5000");
                //设置编码格式
                message.getMessageProperties().setContentEncoding("UTF-8");
                return message;
            }
        };
        rabbitTemplate.convertAndSend("DirectEmail","email", emailEntity.getId(),messagePostProcessor);
//        rabbitTemplate.convertAndSend("DirectEmail","email", emailEntity.getId());
        return DataResult.success();
    }
}
